package array;

public class Matrix {
    private int rows, columns;
    private int[][] element;

    public Matrix(int m, int n) {
        this.element = new int[m][n];
        this.rows = m;
        this.columns = n;
    }

    public Matrix(int n) {
        this(n, n);
    }

    public Matrix(int m, int n, int[][] value) {
        this(m, n);
        for (int i = 0; i < value.length && i < m; i++)
            for (int j = 0; j < value[i].length && j < n; j++)
                this.element[i][j] = value[i][j];
    }

    public int getRows() {
        return this.rows;
    }

    public int getColumns() {
        return this.columns;
    }

    public int get(int i, int j) {
        if (i >= 0 && i < this.rows && j >= 0 && j < this.columns)
            return this.element[i][j];
        throw new IndexOutOfBoundsException("i=" + i + "，j=" + j);
    }

    public void set(int i, int j, int x) {
        if (i >= 0 && i < this.rows && j >= 0 && j < this.columns)
            this.element[i][j] = x;
        else throw new IndexOutOfBoundsException("i=" + i + "，j=" + j);
    }

    public String toString() {
        String str = " 矩阵" + this.getClass().getName() + "（" + this.rows + "×" + this.columns + "）：\n";
        for (int i = 0; i < this.rows; i++) {
            for (int j = 0; j < this.columns; j++)
                str += String.format("%6d", this.element[i][j]);
            str += "\n";
        }
        return str;
    }

    public void add(Matrix matrix) {
        for (int i = 0; i < this.rows; i++) {
            for (int j = 0; j < this.columns; j++)
                this.set(i, j, this.get(i, j) + matrix.get(i, j));
        }
    }

    public static void main(String args[]) {
        int[][] value1 = {
                            {11, 12, 13, 14, 15},
                            {21, 22, 23, 24, 25},
                            {31, 32, 33, 34, 35},
                            {41, 42, 43, 44, 45}
        };
        Matrix matrix = new Matrix(4, 5, value1);
        System.out.println(matrix);
        System.out.println(matrix.getRows());
        System.out.println(matrix.getColumns());

        matrix.set(2, 3, 100);
        System.out.print(matrix);


        int[][] value2 = {
                {1, 1, 1, 1, 1},
                {1, 1, 1, 1, 1},
                {1, 1, 1, 1, 1},
                {1, 1, 1, 1, 1}
        };
        Matrix matrix2 = new Matrix(4, 5, value2);
        matrix.add(matrix2);
        System.out.print(matrix);
    }
}
